package com.t4.courseware.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.t4.courseware.common.CommonPage;
import com.t4.courseware.common.Result;
import com.t4.courseware.config.AliyunConfig;
import com.t4.courseware.handler.UserThreadLocal;
import com.t4.courseware.mapper.CoursewareMapper;
import com.t4.courseware.mapper.UserCoursewareMapper;
import com.t4.courseware.pojo.Courseware;
import com.t4.courseware.pojo.UserCourseware;
import com.t4.courseware.pojo.dto.CoursewareDto;
import com.t4.courseware.pojo.dto.UserDto;
import com.t4.courseware.service.CoursewareService;
import com.t4.courseware.utils.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CoursewareServiceImpl extends ServiceImpl<CoursewareMapper, Courseware> implements CoursewareService {

    // 允许上传图片的格式
    private static final String[] IMAGE_TYPE = {".bmp", ".jpg", ".jpeg", ".gif", ".png", ".gif"};
    // 允许上传资源文件的格式
    private static final String[] RESOURCE_TYPE = {".bmp", ".jpg", ".jpeg", ".gif", ".png", ".gif", ".txt", ".pdf", ".doc", ".docx", ".ppt", ".zip", ".rar", ".html"};

    @Resource
    private CoursewareMapper coursewareMapper;

    @Resource
    private UserCoursewareMapper userCoursewareMapper;

    @Autowired
    private OSS ossClient;

    @Autowired
    private AliyunConfig aliyunConfig;

    @Override
    public Result list(Integer start) {
        IPage<Courseware> page = new Page<>(start, 10);
        IPage<Courseware> coursewareIPage = coursewareMapper.selectPage(page, null);
        List<Courseware> collect = coursewareIPage.getRecords().stream().peek(x -> x.setUrl(null)).collect(Collectors.toList());
        coursewareIPage.setRecords(collect);
        return Result.SUCCESS(CommonPage.restPage(coursewareIPage));
    }

    @Override
    @Transactional
    public Result upload(CoursewareDto coursewareDto) {

        // 1. insert courseware
        UserDto userDto = UserThreadLocal.get();
        Courseware courseware = new Courseware();
        BeanUtils.copyProperties(coursewareDto, courseware);
        courseware.setUploadUserId(userDto.getId());
        coursewareMapper.insert(courseware);
        // 2. update user_courseware
        UserCourseware userCourseware = new UserCourseware();
        userCourseware.setUserId(userDto.getId());
        userCourseware.setCwId(courseware.getId());
        userCoursewareMapper.insert(userCourseware);
        return Result.SUCCESS(true);
    }

    @Override
    public Result search(String key) {
        List<Courseware> coursewareList = coursewareMapper.selectList(new LambdaQueryWrapper<Courseware>().like(Courseware::getName, key));
        return Result.SUCCESS(coursewareList);
    }

    @Override
    public Result uploadCover(MultipartFile multipartFile) {
        // 1. 图片校验，进行后缀名校验
        boolean isLegal = false;
        for(String type: IMAGE_TYPE){
            // 忽略大小写校验后缀名是否符合允许上传的格式
            if(StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)){
                isLegal = true;
                break;
            }
        }
        // 不符合就设置文件上传状态为error
        if(!isLegal){
            return Result.FAIL();
        }

        // 2. 构建文件的新全路径名
        String ossFilePath = FileUtils.getOssFilePath(aliyunConfig.getCoverRootDic(), multipartFile.getOriginalFilename());

        try{
            // 3. 上传文件到阿里云OSS
            ossClient.putObject(aliyunConfig.getBucketName(), ossFilePath, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (OSSException | ClientException | IOException e) {
            return Result.FAIL();
        }

        // 上传成功
        return Result.SUCCESS("/" + ossFilePath);
    }


    @Override
    public Result uploadResource(MultipartFile multipartFile) {
        // 1. 文件校验，进行后缀名校验
        boolean isLegal = false;
        for(String type: RESOURCE_TYPE){
            // 忽略大小写校验后缀名是否符合允许上传的格式
            if(StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(), type)){
                isLegal = true;
                break;
            }
        }
        // 不符合就设置文件上传状态为error
        if(!isLegal){
            return Result.FAIL();
        }

        // 2. 构建文件的新全路径名
        String ossFilePath = FileUtils.getOssFilePath(aliyunConfig.getResourceRootDic(), multipartFile.getOriginalFilename());

        try{
            // 3. 上传文件到阿里云OSS
            ossClient.putObject(aliyunConfig.getBucketName(), ossFilePath, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (OSSException | ClientException | IOException e) {
            return Result.FAIL();
        }

        // 上传成功
        return Result.SUCCESS("/" + ossFilePath);
    }


}
